/*
  * @file JSonFileReader.cpp
  * @author Thibault Merle et Guillaume Poussel
  */
#include <vector>
#include <cstdlib>
#include <fstream>

#include "base/point_list.h"
#include "base/Point.h"
#include "io/JsonFileReader.h"

point_list JsonFileReader::read_points() const {
    point_list points;
    std::ifstream in(_filename);
    if (!in) {
        return points;
    }
    std::string file;
    std::string line;
    while ((in >> line)) {
        file += line;
    }
    // file est le fichier sans aucun caractère d'espacement
    unsigned int start = file.find_first_of("'points':[") + 10;
    unsigned int end = file.find_first_of("]", start);
    std::string points_str = file.substr(start, end-start);
    // points_str est le tableau au format JSON
    start = 0;
    end = 0;
    while (start < points_str.length()-1) {
        start = points_str.find_first_of("{", start);
        end = points_str.find_first_of("}", start);
        std::string pt_str = points_str.substr(start, end-start+1);
        int start_pt = pt_str.find_first_of(":");
        int end_pt = pt_str.find_first_of(",");
        p_type x = std::atof(pt_str.substr(start_pt+1, end_pt-start_pt).c_str());
        start_pt = pt_str.find_first_of(":", start_pt+1);
        end_pt = pt_str.find_first_of("}");
        p_type y = std::atof(pt_str.substr(start_pt+1, end_pt-start_pt).c_str());
        points.push_back(new Point(x, y));
        start = end;
    }
    return points;
}
